﻿using CsvHelper;
using CsvHelper.Configuration;
using Dapper;
using guidHelper;
using Microsoft.Data.SqlClient;
using MyDapperApi.Models;
using MySql.Data.MySqlClient;
using QYWXUpdate.DataModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Globalization;
using System.Reflection;
using System.Text;

namespace MyDapperApi.Services;
/// <summary>
/// 通用数据库查询方法
/// </summary>
public class CsvService : ICsvService
{
    private readonly IConfiguration _configuration;
    private readonly string _csvFilePath;


    public CsvService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public async Task<CommonResponse>AppendToCsv<T>(string filePath, List<T> data, ClassMap<T> classMap)
    {
        var result = new CommonResponse();

        bool fileExists = File.Exists(filePath);

        // 创建配置并注册映射
        var config = new CsvConfiguration(CultureInfo.InvariantCulture);

        using (var writer = new StreamWriter(filePath, append: true))
        using (var csv = new CsvWriter(writer, config))
        {
            // 注册映射类
            csv.Context.RegisterClassMap(classMap);

            // 如果文件不存在，写入表头（会应用映射配置）
            if (!fileExists)
            {
                csv.WriteHeader<T>();
                csv.NextRecord();
            }

            // 写入数据（会应用映射配置）
            csv.WriteRecords(data);
        }

        result.SetSuccess();
        return result;
    }

}